<?php


namespace app\admin\controller;

use app\admin\controller\BaseController;
use app\admin\service\Token;
use app\common\exception\MessageException;
use app\common\model\mysql\system\User as UserModal;
use app\common\validate\PasswordValidate;

class Passport extends BaseController
{
    public function login()
    {
        (new PasswordValidate())->goCheck();
        $data = $this->request->param();
        try {
            $Modal = new UserModal();
            $user = $Modal->where('username', '=', $data['username'])->find();

            if (!$user || $user->delete_time) {
                return $this->renderData('用户名或者密码不正确', 20000);
            }
            // var_dump($user);
            if ($user->password !== md5($data['password'] . config('setting.pwd_salt'))) {
                return $this->renderData('用户名或者密码不正确', 20000);
            }
            // 登录成功 TODO 更新用户操作日志 是否需要管理 session
            // session(config('setting.session_scope'), $user);
            $user->hidden(['status', 'password', 'create_time', 'update_time']);
            // 缓存数据 生成token
            $tokenService = new Token();
            $token = $tokenService->getToken($user);
            return $this->renderSuccess(['token' => $token, 'user' => $user]);
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function logout($token)
    {
        // 删除缓存数据 需要判断token是否本用户
        // cache($token, NULL);
    }
}